package com.pdg.mcplugin.tsa;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.bukkit.Material;

import com.pdg.mcplugin.common.baseclasses.DataProviderBase;

public class DataProvider extends DataProviderBase<TSA> {
	private static final String CONNECTION_STRING = "jdbc:sqlite:%s"+ File.separator + "tsa.db";
	private static final String LEGACY_TABLE_BLOCKS = "tsa_blocks";
	private static final String LEGACY_TABLE_CONTRABAND = "tsa_contraband";
	private static final String LEGACY_FIELD_MATERIAL_ID = "material_id";
	private static final String LEGACY_TABLE_ARRIVALS = "tsa_arrivals";
	private static final String DB_RETRIEVE_ALL_LEGACY_CONTRABAND = "SELECT `"+LEGACY_FIELD_MATERIAL_ID+"`  FROM `"+LEGACY_TABLE_CONTRABAND+"`;";

	public DataProvider(TSA thePlugin) {
		super(thePlugin,CONNECTION_STRING);
	}

	public void upgradeDatabase() {
		upgradeDatabaseTo1_3_1_2();
	}

	private void upgradeDatabaseTo1_3_1_2() {
		upgradeArrivalsTable1_3_1_2();
		upgradeContrabandTable1_3_1_2();
		upgradeBlocksTable1_3_1_2();
	}

	private void upgradeBlocksTable1_3_1_2() {
		//remove blocks table if it exists
		dropTable(LEGACY_TABLE_BLOCKS);
	}

	private void upgradeContrabandTable1_3_1_2() {
		//check for contraband table
		if(doesTableExist(LEGACY_TABLE_CONTRABAND)){
			//grab all entries from contraband table
			Set<Integer> materialIds = new HashSet<Integer>();
			try {
				Statement statement;
				statement = getConnection().createStatement();
				ResultSet result = statement.executeQuery(DB_RETRIEVE_ALL_LEGACY_CONTRABAND);
				
				while(result.next()){
					materialIds.add(result.getInt(LEGACY_FIELD_MATERIAL_ID));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			//write all entries to default contraband list
			String theDefaultList = getPlugin().getContrabandManager().getDefaultList();
			ContrabandList theContrabandList = getPlugin().getContrabandManager().getContrabandList(theDefaultList);
			Iterator<Integer> iterator = materialIds.iterator();
			while(iterator.hasNext()){
				Integer theMaterialId = iterator.next();
				Material theMaterial = Material.getMaterial(theMaterialId);
				theContrabandList.add(theMaterial,false);
			}
			//remove contraband table
			dropTable(LEGACY_TABLE_CONTRABAND);
		}
	}

	private void upgradeArrivalsTable1_3_1_2() {
		//check for arrivals table
		if(doesTableExist(LEGACY_TABLE_ARRIVALS)){
			//if no table, bail
			//load entries from arrivals table
			//add contraband list value of "default"
			//save entries to destinations table
			//remove arrivals table
		}
	}

}
